package com.ruoyi.customer.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.customer.SentMessage;
import com.ruoyi.customer.domain.TCommentRecord;
import com.ruoyi.customer.domain.bo.TCommentRecordBo;
import com.ruoyi.customer.domain.vo.TCommentRecordVo;
import com.ruoyi.customer.mapper.TCommentRecordMapper;
import com.ruoyi.customer.service.ITCommentRecordService;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.service.ISysConfigService;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

/**
 * 点评信息记录Service业务层处理
 *
 * @author ruoyi
 * @date 2023-10-18
 */
@RequiredArgsConstructor
@Service
public class TCommentRecordServiceImpl implements ITCommentRecordService {

    private final TCommentRecordMapper baseMapper;
    private final SysUserMapper userMapper;
    private final ISysConfigService sysConfigService;

    /**
     * 查询点评信息记录
     */
    @Override
    public TCommentRecordVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询点评信息记录列表
     */
    @Override
    public TableDataInfo<TCommentRecordVo> queryPageList(TCommentRecordBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<TCommentRecord> lqw = buildQueryWrapper(bo);
        Page<TCommentRecordVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询点评信息记录列表
     */
    @Override
    public List<TCommentRecordVo> queryList(TCommentRecordBo bo) {
        LambdaQueryWrapper<TCommentRecord> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<TCommentRecord> buildQueryWrapper(TCommentRecordBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<TCommentRecord> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getCustomerId() != null, TCommentRecord::getCustomerId, bo.getCustomerId());

        lqw.eq(StringUtils.isNotBlank(bo.getContent()), TCommentRecord::getContent, bo.getContent());
        lqw.eq(bo.getNoticeTime() != null, TCommentRecord::getNoticeTime, bo.getNoticeTime());
        lqw.eq(bo.getIsOpen() != null, TCommentRecord::getIsOpen, bo.getIsOpen());
        lqw.eq(bo.getCreateId() != null, TCommentRecord::getCreateId, bo.getCreateId());
        lqw.eq(StringUtils.isNotBlank(bo.getStatus()), TCommentRecord::getStatus, bo.getStatus());
        lqw.like(StringUtils.isNotBlank(bo.getCustomerName()), TCommentRecord::getCustomerName, bo.getCustomerName());
        lqw.like(StringUtils.isNotBlank(bo.getUserName()), TCommentRecord::getUserName, bo.getUserName());
        lqw.eq(StringUtils.isNotBlank(bo.getCustomerTel()), TCommentRecord::getCustomerTel, bo.getCustomerTel());

        lqw.eq(TCommentRecord::getCreateId, LoginHelper.getUserId());
        lqw.orderByDesc(TCommentRecord::getId);
        return lqw;
    }

    /**
     * 新增点评信息记录
     */
    @Override
    public Boolean insertByBo(TCommentRecordBo bo) {
        TCommentRecord add = BeanUtil.toBean(bo, TCommentRecord.class);
        validEntityBeforeSave(add);
        add.setCreateId(LoginHelper.getUserId());
        Optional.ofNullable(userMapper.selectUserById(bo.getUserId())).ifPresent(it->{
            add.setUserName(it.getNickName());
        });
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
            sentMessage(add, LoginHelper.getLoginUser().getNickName());
        }
        return flag;
    }

    private void sentMessage(TCommentRecord commentRecord, String operationName) {
        if (!Objects.isNull(commentRecord.getNoticeTime())) {
            return;
        }
        String commentFlag = sysConfigService.selectConfigByKey(Constants.COMMENT_RECORD);
        if (Objects.equals("1", commentFlag)) {
            SentMessage send = new SentMessage();
            send.setType(Constants.MESSAGE_COMMENT_RECORD);
            Map<String, String> map = new HashMap<>();
            map.put("info", "客户信息：" + commentRecord.getCustomerName() + "【 " + commentRecord.getCustomerTel() + " 】" + "</br>"
                    + "来自主管: 【" + commentRecord.getCreateBy() + "】的点评信息：" + commentRecord.getContent());
            send.setContent(JSONObject.toJSONString(map));
            List<String> userList = new ArrayList<>();
            userList.add(String.valueOf(commentRecord.getUserId()));
            send.setUserIds(userList);
            send.setOperationName(operationName);
            SpringUtils.context().publishEvent(send);
        }
    }

    /**
     * 修改点评信息记录
     */
    @Override
    public Boolean updateByBo(TCommentRecordBo bo) {
        TCommentRecord update = BeanUtil.toBean(bo, TCommentRecord.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(TCommentRecord entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除点评信息记录
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }
}
